package com.yiyi.word_test.controller;

import com.yiyi.word_test.dto.GradeCountDTO;
import com.yiyi.word_test.service.HistoryService;
import com.yiyi.word_test.util.ResultVOUtil;
import com.yiyi.word_test.vo.HistoryVO;
import com.yiyi.word_test.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/history")
public class HistoryController {

    @Autowired
    private HistoryService historyService;

    // 前端返回答题情况，计算分数并存入数据库
    @PostMapping("/calculateScore")
    public ResultVO calculateScore(@RequestBody GradeCountDTO gradeCountDTO) {
        // 先计算结果
        Integer score = historyService.calculateScore(gradeCountDTO);
        // 后写入数据库
        historyService.saveHistory(gradeCountDTO.getOpenId(), gradeCountDTO.getGrade(), score);
        // 最后返回数据
        return ResultVOUtil.success(score);
    }

    // 通过openid获取历史记录
    @GetMapping("/getHistoryByOpenId/{userOpenId}")
    public ResultVO getHistoryByOpenId(@PathVariable("userOpenId") String userOpenId) {
        List<HistoryVO> historyVOS = historyService.getHistory(userOpenId);

        if (historyVOS.isEmpty()) {
            return ResultVOUtil.isNull();
        } else {
            return ResultVOUtil.success(historyVOS);
        }
    }
}